export const toPath = (url) => {
    if (!url.startsWith('/')) {
        url = '/' + url
    }
    uni.navigateTo({url})
}

export const getUserInfo = () => {
    return uni.getStorageSync("user_info")
}
export const getCtUserInfo = () => {
    return getUserInfo()?.ctUserInfo || {};
}
export const getUserName = () => {
    return getCtUserInfo()?.name;
}

export const toBack = () => {
    uni.navigateBack()
}

export const scanCode = () => {
    return new Promise((resolve, reject) => {
        uni.scanCode({
            success: (res) => {
                resolve(res.result)
            },
            fail: (err) => {
                reject(err)
            }
        })
    })
}
export const makePhoneCall = (phone) => {
    uni.makePhoneCall({
        phoneNumber: phone //仅为示例
    });
}

export const GeoUtils = {
    toRadians(degrees) {
        return degrees * Math.PI / 180;
    },

    calculateDistance(pointA, pointB) {
        const EARTH_RADIUS = 6371; // 单位为公里
        const lat1 = this.toRadians(pointA.lat);
        const lon1 = this.toRadians(pointA.lon);
        const lat2 = this.toRadians(pointB.lat);
        const lon2 = this.toRadians(pointB.lon);

        const dLat = lat2 - lat1;
        const dLon = lon2 - lon1;

        const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(lat1) * Math.cos(lat2) *
            Math.sin(dLon / 2) * Math.sin(dLon / 2);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return EARTH_RADIUS * c * 1000;
    }

}


export class LocationUtils {
    /**
     * 检查并请求定位权限，提供自定义提示
     * @param {string} permissionTip 授权提示信息
     * @returns {Promise<boolean>} 是否已获得授权
     */
    static async checkAndRequestPermission(permissionTip = '需要您的位置授权') {
        return new Promise((resolve) => {
            uni.getSetting({
                success: (res) => {
                    if (!res.authSetting['scope.userLocation']) {
                        uni.showModal({
                            title: '提示',
                            content: permissionTip,
                            showCancel: false,
                            success: () => {
                                uni.authorize({
                                    scope: 'scope.userLocation',
                                    success: () => {
                                        resolve(true);
                                    },
                                    fail: () => {
                                        resolve(false);
                                    },
                                });
                            },
                        });
                    } else {
                        resolve(true);
                    }
                },
                fail: () => {
                    resolve(false);
                },
            });
        });
    }

    /**
     * 获取当前位置信息，支持自定义提示和定位参数
     * @param {Object} options 定位参数，参考uni-app官方文档
     * @param {string} [failTip='获取位置信息失败，请重试'] 定位失败时的提示信息
     * @returns {Promise<Object>} 定位信息对象
     */
    static async getLocation(options = {}, failTip = '获取位置信息失败，请重试') {
        await this.checkAndRequestPermission();

        return new Promise((resolve, reject) => {
            uni.getLocation({
                type: 'wgs84',
                altitude: true,
                failTip: '无法获取您的位置，请确保已开启定位服务',
                ...options,
                success: (res) => {
                    console.log("获取位置信息", res)
                    this.getCoordinate(res)
                        .then(address => resolve({...res, address})).catch(reject)
                },
                fail: (err) => {
                    uni.showToast({
                        icon: 'none',
                        title: failTip,
                    });
                    reject(err);
                },
            });
        });
    }

    static async getCoordinate({longitude, latitude}) {
        const apiKey = 'ffabd9232b501455009caf9a71a2ae44';
        const geocodingUrl = `https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${longitude},${latitude}&output=json&radius=1000&extensions=all`;

        try {
            const {data = {}} = await uni.request({url: geocodingUrl});
            if (data.info === 'OK' && data.regeocode) {
                return data.regeocode.formatted_address;
            } else {
                throw new Error('Failed to get address information');
            }
        } catch (error) {
            console.error('Error fetching address:', error);
            throw error;
        }
    }
}

export const Msg = {
    success(msg) {
        uni.showToast({
            title: msg,
            icon: 'success',
            duration: 2000
        })
    },
    error(msg) {
        uni.showToast({
            title: msg,
            icon: 'error',
            duration: 2000
        })
    },
    info(msg) {
        uni.showToast({
            title: msg,
            icon: 'none',
            duration: 2000
        })
    },
    loading(handler, msg) {
        uni.showLoading({title: msg || "加载中...", mask: true });
        handler?.(() => uni.hideLoading())
    },
    confirm(message) {
        return new Promise((resolve, reject) => {
            uni.showModal({
                title: '提示',
                content: message,
                success: function (res) {
                    res.confirm ? resolve() : reject()
                }
            })
        })
    }
}

export class DateUtil {

    static format(date, format) {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hour = date.getHours().toString().padStart(2, '0');
        const minute = date.getMinutes().toString().padStart(2, '0');
        const second = date.getSeconds().toString().padStart(2, '0');

        return format
            .replace('YYYY', year)
            .replace('MM', month)
            .replace('DD', day)
            .replace('HH', hour)
            .replace('mm', minute)
            .replace('ss', second);
    }

    static getCurrDateTime() {
        return this.format(new Date(), 'YYYY-MM-DD HH:mm:ss')
    }
}
